package com.hgkj.cloud.base.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.SFTPv3DirectoryEntry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

@Slf4j
public class FileUtil {
	public static String prefixUrl = "/";
	public static SFTPv3Client sftpClient;
	public static List<String> list = new ArrayList<String>();
	public static String ip;
	public static String username;
	public static String password;
	public static Connection con;
	public static String baseDir;//服务器使用
	public static String localBaseDir;//本地使用

	public static void init(String ip, String username, String password) throws IOException {
		con = new Connection(ip, 22);
		con.connect();
		con.authenticateWithPassword(username, password);
		sftpClient = new SFTPv3Client(con);
	}

	public static void listFiles(SFTPv3Client sftpClient, String rootdir, String basedir, List<String> list)
			throws IOException {

		Vector v = sftpClient.ls(rootdir + basedir);
		Iterator it = v.iterator();
		while (it.hasNext()) {
			SFTPv3DirectoryEntry sde = (SFTPv3DirectoryEntry) it.next();
			if (!sde.attributes.isDirectory()) {

				list.add(prefixUrl + "resource/" + basedir + "/" + sde.filename);
			} else if (sde.filename.endsWith(".") || sde.filename.equals("..")) {
				continue;
			} else {
				listFiles(sftpClient, rootdir, basedir + "/" + sde.filename, list);
			}
		}
	}

	/**
	 * 上传文件至125主服务器
	 * @param fileUrls 文件网络路径数组   ps:https://www.huichengyun.com/news/cloud4099469748974037836.png
	 * @param oldFileUrls 旧文件网络路径数组
	 * @param prefix 网络路径前缀 ps:https://www.huichengyun.com/
	 */
	public static void uploadFileToServer(String[] fileUrls,String[] oldFileUrls,String prefix) throws IllegalStateException{
		if (oldFileUrls != null && oldFileUrls.length > 0) {
			for (int i = 0; i < oldFileUrls.length; i++) {
				oldFileUrls[i] = FilenameUtils.getFullPathNoEndSeparator(prefix) + oldFileUrls[i];
			}
		}
		if (fileUrls != null && fileUrls.length > 0) {
			for (int j = 0; j < fileUrls.length; j++) {
				fileUrls[j] = FilenameUtils.getFullPathNoEndSeparator(prefix) + fileUrls[j];
			}
		}
		if (fileUrls.length > 0) {
			try {
				if(ip.equals("127.0.0.1")){
					return;
				}
				InetAddress addr = InetAddress.getLocalHost();
				String localIp = addr.getHostAddress().toString(); // 获取本机ip
				if (!localIp.equals(ip)) {
					init(ip, username, password);
					SCPClient scpClient = con.createSCPClient();
					//上传文件至125主服务
					for (int j = 0; j < fileUrls.length; j++) {
						String fileUrl = fileUrls[j];
						if (fileUrl != null && !fileUrl.equals("")) {
							// 截取除域名和文件名外的字符串
							String serverDir = StringUtils.replace(FilenameUtils.getFullPathNoEndSeparator(fileUrl),
									prefixUrl, "");
							String[] dirNames = (baseDir + serverDir).split("/");
							List<String> dirList = new ArrayList<String>();
							for (int i = 4; i < dirNames.length; i++) {
								String dirName = dirNames[i];
								String serverDirStr = "";
								if (dirList.size() == 0) {
									serverDirStr = baseDir + dirName + "/";
								} else {
									serverDirStr = dirList.get(dirList.size() - 1) + dirName + "/";
								}
								try {
									// 创建文件夹
									sftpClient.mkdir(serverDirStr, 0777);
								} catch (IOException e) {
									e.printStackTrace();
								}
								dirList.add(serverDirStr);
							}
							// 拼接本地文件地址
							String localFile = fileUrl.replace(prefixUrl, baseDir);
//							String localFile = fileUrl.replace(prefixUrl, localBaseDir);
							// 上传文件至主服务器
							scpClient.put(localFile, FilenameUtils.getName(fileUrl), dirList.get(dirList.size() - 1),"0777");
							// 删除非主服务器文件
							File f = new File(localFile);
							f.delete();
						}
					}
					//删除旧文件
					if (oldFileUrls != null && oldFileUrls.length > 0) {
						for (int i = 0; i < oldFileUrls.length; i++) {
							String oldFile = oldFileUrls[i];
							if (oldFile != null && !oldFile.equals("")) {
								try {
									String remoteFile = oldFile.replace(prefixUrl, baseDir);
									sftpClient.rm(remoteFile);
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}
				}
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}catch (IllegalStateException e) {
				throw new IllegalStateException(e);
			} finally {
				if (con != null) {
					con.close();
				}
			}
		}
	}
	
	/**
	 * 递归删除文件夹及其文件
	 * @param f
	 */
	public static void recurDelete(File f) {
		try {
			for (File fi : f.listFiles()) {
				if (fi.isDirectory()) {
					recurDelete(fi);
				} else {
					fi.delete();
				}
			}
			f.delete();
		} catch (NullPointerException n) {
		}

	}

	/**
	 * 文件下载
	 *
	 * @param response 响应
	 * @param downFileName     名称
	 * @param filepath     文件路径
	 * @param delFile  下载之后是否删除原文件
	 * @throws IOException
	 */
	public static void downloadFile(HttpServletResponse response, String downFileName, String filepath, Boolean delFile) throws IOException {
		log.info("downloadFile: " + filepath);
		FileInputStream inp = null;
		OutputStream out = null;
		File file = new File(filepath);
		downFileName = downFileName == null ? file.getName() : downFileName;
		if (!downFileName.contains(".") && file.getName().contains(".")) {
			downFileName = downFileName + file.getName().substring(file.getName().indexOf("."));
		}
		try {
			inp = new FileInputStream(file);
			response.addHeader("Content-Disposition", "attachment;filename=\"" + java.net.URLEncoder.encode(downFileName, "utf-8") + "\"");
			response.addHeader("Content-Length", "" + file.length());
			response.setContentType("application/octet-stream");
			out = new BufferedOutputStream(response.getOutputStream());
			FileCopyUtils.copy(inp, out);
			//删除临时文件
			if (file.exists() && delFile) {
				file.delete();
			}
		}
		catch (Exception e) {
			log.error("downloadFile exception", e);
		}
		finally {
			try {
				if (out != null)
					out.close();
				if (inp != null)
					inp.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void writeFile(File file, String data) {
		FileWriter fileWriter = null;
		try {
			File dir = file.getParentFile();
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 检查目标文件是否存在，不存在则创建
			if (!file.exists()) {
				file.createNewFile();// 创建目标文件
			}
			// FileWriter(File file, boolean append)，append为true时为追加模式，false或缺省则为覆盖模式
			fileWriter = new FileWriter(file, true);
			// 向目标文件中写入内容
			fileWriter.append(data + "\n\n");
			fileWriter.flush();
			log.info("写入成功!!!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 将文件转换成byte数组
	 * @param file  文件File类 通过new File(文件路径)
	 * @return byte数组
	 */
	public static byte[] File2byte(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	//将Byte数组转换成文件
	public static File getFileByBytes(byte[] bytes, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists()) {//判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			if (file.exists()) {
				file.delete();
			}
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
				}
			}
		}
		return file;
	}

//	public static void main(String[] args) throws IOException {
		//			init(ip, username, password);
//		uploadFileToServer(null);
//		uploadFileToServer("");
//		List<String> oldList = new ArrayList<String>();
//		oldList.add("https://www.huichengyun.com/yinlhTest/thumbnail/cloud388406237750858574.jpg");
//		oldList.add("https://www.huichengyun.com/yinlhTest/cloud388406237750858574.jpg");
//		String[] oldstrs = oldList.toArray(new String[]{});
//		List<String> newList = new ArrayList<String>();
//		newList.add("https://www.huichengyun.com/yinlhTest/thumbnail/cloud388406237750858573.jpg");
//		newList.add("https://www.huichengyun.com/yinlhTest/cloud388406237750858573.jpg");
//		String[] newstrs = newList.toArray(new String[]{});
//		uploadFileToServer(newstrs,oldstrs);
//		//生成单个ai报告
//		Properties properties = new Properties();
//		// 使用InPutStream流读取properties文件
//		BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\yinyh\\cloud-parent\\cloud-customer\\src\\main\\webapp\\WEB-INF\\config.dev.properties"));
//		properties.load(bufferedReader);
//		// 获取key对应的value值
//		String Host = properties.getProperty("server.host");
//		String aiHost = properties.getProperty("ai.host");
//	}
}
